package com.cvte.boe.media.player.retrieve;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.SystemClock;

import com.cvte.boe.media.utils.LogUtil;

import java.util.ArrayList;

/**
 * Created by wuguitong on 2018/5/17.
 */
public class AsyncRetrieveAudio implements Runnable{
    private boolean isStop = false;
    private static final String NO_FILE = "";
    private ArrayList<String> mWaitingQueue = new ArrayList();
    private MediaMetadataRetriever mRetriever = null;
    private Context mContext;
    private RetrieveAudioCompleteListener retrieveAudioCompleteListener = null;
    public AsyncRetrieveAudio(Context context){
        this.mContext = context;
    }
    @Override
    public void run() {
        while (!isStop){
            String file = NO_FILE;
            file = getLastTask();
            if(file.equals(NO_FILE)){
                SystemClock.sleep(100);
                continue;
            }
            mRetriever = new MediaMetadataRetriever();
            mRetriever.setDataSource(mContext, Uri.parse(file));
            byte[] coverPic = mRetriever.getEmbeddedPicture();
            if(coverPic != null && retrieveAudioCompleteListener != null) {
                retrieveAudioCompleteListener.onCompleteAlbum(file,BitmapFactory.decodeByteArray(coverPic, 0, coverPic.length));
            }else {
                retrieveAudioCompleteListener.onCompleteAlbum(file,null);
            }
            mRetriever.release();
        }
    }
    public synchronized void addTask(String filename){
        if(filename == null){
            return;
        }
        mWaitingQueue.add(filename);
    }
    private synchronized String getLastTask(){
        int len = mWaitingQueue.size();
        String file = NO_FILE;
        if(len > 0){
            file = mWaitingQueue.get(len -1);
            mWaitingQueue.clear();
        }
        return file;
    }
    public void killSelf(){
        isStop = true;
    }

    public void setRetrieveAudioCompleteListener(RetrieveAudioCompleteListener retrieveAudioCompleteListener) {
        this.retrieveAudioCompleteListener = retrieveAudioCompleteListener;
    }
    public void removeRetrieveAudioCompleteListener() {
        this.retrieveAudioCompleteListener = null;
    }
}
